package com.btr.uimeter.logger;

import java.io.IOException;
import java.io.Writer;
import java.util.logging.Logger;

import com.btr.uimeter.UIMeterEvent;
import com.btr.uimeter.UIMeterEventHandler;
import com.btr.uimeter.probes.UIMeterProbe;

/*****************************************************************************
 * Logs the probing event data to a Writer.
 * This will generate one text line per event.
 * Use this to persist the probing data to text files or the console.
 * 
 * @author Bernd Rosstauscher (java@rosstauscher.de) Copyright 2010
 ****************************************************************************/

public class UIMeterEventWriter implements UIMeterEventHandler {

	private Writer writer;
	
	/*************************************************************************
	 * Constructor
	 * @param output to write to.
	 ************************************************************************/
	
	public UIMeterEventWriter(Writer output) {
		super();
		this.writer = output;
	}

	/*************************************************************************
	 * processEvent
	 * @see com.btr.uimeter.UIMeterEventHandler#processEvent(UIMeterProbe, UIMeterEvent)
	 ************************************************************************/
	
	public void processEvent(UIMeterProbe producer, UIMeterEvent e) {
		try {
			String line = formatEventAsString(e);
			this.writer.write(line);
		} catch (IOException e1) {
			logError("processEvent", e1);
		}
	}
	
	/*************************************************************************
	 * Converts a log event to a line that is then written to the output backend.
	 * @param e the event to convert.
	 * @return the string message for the event.
	 ************************************************************************/
	
	protected String formatEventAsString(UIMeterEvent e) {
		return e.getType()+"\t"+e.getData()+"\n";
	}

	/*************************************************************************
	 * Logs an exception to the java.util.logger framework.
	 * @param source of the error
	 * @param e1 the exception that occurred.
	 ************************************************************************/
	
	protected void logError(String source, IOException e1) {
		Logger logger = Logger.getLogger("UIMeter");
		logger.throwing(UIMeterEventWriter.class.getCanonicalName(), source, e1);
	}

	/*************************************************************************
	 * close
	 * @see com.btr.uimeter.UIMeterEventHandler#close()
	 ************************************************************************/
	
	public void close() {
		try {
			this.writer.close();
		} catch (IOException e) {
			logError("close", e);
		}
	}

}
